import { setUserInfo } from '@/utils/storage.js'
import { setLocalUserAuthority, getLocalUserAuthority } from '@/utils/service'
import { handleRequestStatus } from '@/utils/uitls.js'
import ROUTER from '@/router/router'

// request
import { getLogout } from '@/api/login/index.js'

const session = window.sessionStorage

export const createForm = () => ({
  // userAccount: 'admin-007',
  // passWord: '525678',
  userAccount: '',
  passWord: '',
  loginType: '1', // 登陆类型：1 ：管理端界面登陆 2:媒体端界面登陆
})

export const createRules = () => ({
  userAccount: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
  passWord: [{ required: true, message: '密码不能为空', trigger: 'blur' }],
})

export const keyStr = 'A18z1Rsz9G23tbv8'
export const ivStr = 'A18z1Rsz9G23tbv8'

export const handleUserInfo = (data) => {
  // userInfo
  setUserInfo(data)

  // resource
  const dataStorage = window.sessionStorage
  dataStorage.setItem('resource', JSON.stringify(data.resource || []))

  // user authority token
  if (process.env.NODE_ENV === 'development') {
    data.userType = 'manager'
  }
  const end = data.userType === 'manager' ? 'manageEnd' : 'provideEnd'
  setLocalUserAuthority(end) // manageEnd | provideEnd
}

export const clearUserInfo = () => {
  session.removeItem('resource')
  session.removeItem('userAuthority')
  session.removeItem('userInfo')
}

export const handleLogout = () => {
  const userAuthority = getLocalUserAuthority()
  clearUserInfo()
  if (process.env.NODE_ENV === 'development') {
    setTimeout(() => {
      ROUTER.replace('/login')
    }, 500)
    return
  }
  if (userAuthority === 'manageEnd') {
    window.location.href = 'http://10.33.83.226:8008/login'
  } else if (userAuthority === 'provideEnd') {
    /* 不延时无法跳转 todo: 待优化 */
    setTimeout(() => {
      ROUTER.replace('/login')
    }, 500)
  } else {
    setTimeout(() => {
      ROUTER.replace('/login')
    }, 500)
  }
}

export const logout = async () => {
  // console.log(Vue.prototype.$Message.success('123')  )
  const res = await getLogout()
  handleRequestStatus(res, '退出登录', handleLogout)
}
